<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>订单管理</title>
    <style>
        #app{
            padding: 20px;
        }
    </style>
</head>
<body>
<div id="app">
    <!--标题-->
    <h1 style="text-align: center">订单管理</h1>

    <el-form :inline="true" :model="order" class="demo-form-inline">
        <el-form-item label="下单时间">
            <el-date-picker
                    v-model="order.createdAt"
                    type="datetime"
                    placeholder="下单时间"
                    value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
        </el-form-item>

        <el-form-item label="至" prop="ordertime2">
            <el-date-picker
                    v-model="order.endAt"
                    type="datetime"
                    placeholder="下单时间"
                    value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
        </el-form-item>

        <el-form-item label="用户" prop="userAcc">
            <el-input v-model="order.username"  @change="Submit"></el-input>
        </el-form-item>

        <el-form-item label="完成状态">
            <el-select v-model="order.status" placeholder="预约状态">
                <el-option label="请选择状态" value=""></el-option>
                <el-option label="待付款" value="pending_payment"></el-option>
                <el-option label="已付款" value="paid"></el-option>
                <el-option label="已发货" value="shipped"></el-option>
                <el-option label="已完成" value="completed"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="fetchrole">查询</el-button>
        </el-form-item>
    </el-form>

    <el-table
            ref="multipleTable"
            :data="orderData"
            tooltip-effect="dark"
            style="width: 100%">
        <el-table-column
                align="center"
                prop="orderNumber"
                label="订单编号">
        </el-table-column>
        <el-table-column
                align="center"
                prop="username"
                label="用户名">
        </el-table-column>
        <el-table-column
                align="center"
                prop="status"
                label="状态">
        </el-table-column>
        <el-table-column
                align="center"
                prop="productName"
                label="产品名称">
        </el-table-column>
        <el-table-column
                align="center"
                prop="shippingMethod"
                label="运输方式">
            <template slot-scope="scope">
                {{ scope.row.shippingMethod === 'self_pickup' ? '自提' : scope.row.shippingMethod === 'delivery' ? '邮递' : '未知' }}
            </template>
        </el-table-column>
        <el-table-column
                align="center"
                prop="address"
                label="运输地址">
        </el-table-column>
        <el-table-column
                label="下单时间"
                prop="createdAt"
                align="center">
            <template slot-scope="scope">
                <div style="text-align: center;">
                    {{ formatDate(scope.row.createdAt) }}
                </div>
            </template>
        </el-table-column>
        <el-table-column
                align="center"
                label="操作">
            <template slot-scope="scope">
                <el-button
                        v-if="scope.row.status === '已付款'"
                        type="success"
                        size="mini"
                        @click="openShipmentDialog(scope.row.orderId)">确认发货</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="block" style="text-align: center; padding: 20px;">
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[3, 5, 7, 10]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totals">
        </el-pagination>
    </div>

    <!-- 确认发货弹窗 -->
    <el-dialog :visible.sync="shipmentDialogVisible" title="确认发货">
        <el-form :model="shipmentForm" :rules="rules" ref="shipmentForm">
            <el-form-item label="快递单号" prop="trackingNumber">
                <el-input v-model="shipmentForm.trackingNumber" placeholder="请输入快递单号"></el-input>
            </el-form-item>
            <el-form-item label="快递公司" prop="courierCompany">
                <el-input v-model="shipmentForm.courierCompany" placeholder="请输入快递公司名称"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="shipmentDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="confirmShipment">确认</el-button>
        </div>
    </el-dialog>
</div>
<script src="js/vue.js"></script>
<script src="js/element-ui/lib/index.js"></script>
<script src="js/axios-0.18.0.js"></script>
<link rel="stylesheet" href="js/element-ui/lib/theme-chalk/index.css">
<script>
    var vv = new Vue({
        el: "#app",
        data(){
            return{
                order:{
                    createdAt: '',
                    endAt:'',
                    status: '',
                    username: '',
                },
                currentPage: 1,
                dialogVisible: false,
                pageSize:5,
                totals:0,
                orderData: [],
                shipmentDialogVisible: false,
                shipmentForm: { // 初始化为一个对象
                    trackingNumber: '',
                    courierCompany: ''
                },
                currentOrderId: '',
                rules: {
                    trackingNumber: [
                        { required: true, message: '请输入快递单号', trigger: 'blur' }
                    ],
                    courierCompany: [
                        { required: true, message: '请输入快递公司名称', trigger: 'blur' }
                    ]
                }
            }
        },
        methods:{
            handleSizeChange(val) {
                this.pageSize = val;
                this.fetchrole();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.fetchrole();
            },
            //查询全部数据
            findByPages(){
                console.log(666666)
                axios({
                    method: 'get',
                    url: `/Order/select?current=${this.currentPage}&size=${this.pageSize}`
                }).then(resp=>{
                    console.log(resp.data.list)
                    this.totals = resp.data.total
                    this.orderData = resp.data.list
                })
            },

            //搜索框查询
            fetchrole() {
                let params = {
                    createdAt: this.order.createdAt || null,
                    endAt: this.order.endAt||null,
                    status: this.order.status || null,
                    username: this.order.username || null
                };
                // 检查是否有查询参数
                let hasParams = Object.values(params).some(value => value !== null);
                if (hasParams) {
                    this.selectWithData(params);
                } else {
                    this.findByPages();
                }
            },

            //带参数查询
            selectWithData(params) {
                axios({
                    method: "post",
                    url: `/Order/search?current=${this.currentPage}&size=${this.pageSize}`,
                    params: params
                })
                    .then((resp) => {
                        this.totals = resp.data.total
                        this.orderData = resp.data.list
                    })
                    .catch((error) => {
                        console.error('Error fetching data with parameters:', error);
                    });
            },

            // 打开确认发货弹窗
            openShipmentDialog(orderId) {
                this.currentOrderId = orderId;
                this.shipmentDialogVisible = true;
                this.$nextTick(() => {
                    this.$refs.shipmentForm.resetFields();
                });
            },
            formatDate(dateStr) {
                if (!dateStr) return '';
                const date = new Date(dateStr);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                return `${year}年${month}月${day}日，${hours}:${minutes}:${seconds}`;
            },

            // 确认发货
            confirmShipment() {
                this.$refs.shipmentForm.validate((valid) => {
                    let params = {
                        orderId: this.currentOrderId,
                        trackingNumber: this.shipmentForm.trackingNumber,
                        courierCompany: this.shipmentForm.courierCompany
                    };
                    if (valid) {
                        axios({
                            method:'post',
                            url:`/Order/confirmShipment`,
                            params: params
                        }).then((resp) => {
                            if (resp.data.code === 20031) {
                                this.$message.success('确认发货成功');
                                this.shipmentDialogVisible = false;
                                this.shipmentForm.trackingNumber = '';
                                this.shipmentForm.courierCompany = '';
                                this.fetchrole(); // 刷新订单列表
                            } else {
                                this.$message.error(resp.data.msg || '确认发货失败');
                            }
                        })
                            .catch((error) => {
                                console.error('Error confirming shipment:', error);
                                this.$message.error('确认发货失败');
                            });
                    } else {
                        this.$message.error('请填写完整的发货信息');
                    }
                });
            },
        },
        mounted(){
            this.findByPages();
        },
    })
</script>
</body>
</html>